/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.muni.fi.heathrow.daoImpl2;

import cz.muni.fi.heathrow.dao.UserDAO;
import cz.muni.fi.heathrow.entities.User;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author Ufonzak
 */
public class UserDAOImpl implements UserDAO
{

    @PersistenceContext
    private EntityManager manager;

    @Override
    public User get(String username)
    {
        TypedQuery<User> q = manager.createQuery("SELECT u FROM User AS u WHERE u.username = :username", User.class);
        q.setParameter("username", username);
        return q.getSingleResult();
    }

    @Override
    public User get(Long id)
    {
        if (id == null)
            throw new IllegalArgumentException("id is null");

        return manager.find(User.class, id);
    }

    @Override
    public void create(User user)
    {
        if (user == null)
            throw new IllegalArgumentException("user is null");
        if (user.getId() != null)
            throw new IllegalArgumentException("user id is not null");

        manager.persist(user);
    }

    @Override
    public void remove(User user)
    {
        if (user == null)
            throw new IllegalArgumentException("user is null");
        if (user.getId() == null)
            throw new IllegalArgumentException("user id is null");

        manager.remove(user);
    }

    @Override
    public void update(User user)
    {
        if (user == null)
            throw new IllegalArgumentException("user is null");
        if (user.getId() == null)
            throw new IllegalArgumentException("user id is null");

        manager.merge(user);
    }

    @Override
    public List<User> findAll() {
        TypedQuery<User> q = manager.createQuery("FROM User", User.class);
        List<User> res = q.getResultList();

        return res;
    }
    
}
